﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Data.SqlClient;


namespace Clinica_Frba
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {

        }

        private void loginButton_Click(object sender, EventArgs e)
        {   
            Conexion sql = Conexion.getInstance();
            Utility util = Utility.getInstance();

            try
            {
                SqlDataReader reader = sql.execQuery("SELECT id_usuario,contraseña,cantIntentos,inhabilitado "+ 
                                                     "FROM b_sharp.usuarios WHERE id_usuario = '"
                                                     + userBox.Text.ToString() + "';");

                if (reader.Read() && reader.GetString(1) == sha256Encrypt(pwdBox.Text.ToString()))
                {
                    if (reader.GetString(3) == 'S'.ToString())
                        MessageBox.Show("El usuario ha sido bloqueado. Contacte al Administrador");
                    else
                    {
                        updateIntentos(reader.GetString(0), 0);
                        //MessageBox.Show("Bienvenido " + reader.GetString(0));
                        util.setLogin(true);
                        util.setUser(reader.GetString(0));
                        this.Close();
                    }
                }
                else
                {
                    updateIntentos(reader.GetString(0), reader.GetInt32(2) + 1);

                    if (reader.GetInt32(2) + 1 >= 3)
                        MessageBox.Show("El usuario ha sido bloqueado. Contacte al Administrador");
                    else
                        MessageBox.Show("Usuario o password incorrecto");
                }

                reader.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Usuario o password incorrecto");
            }
        }

        public string sha256Encrypt(string code)
        {
            string codeEncrypted = string.Empty;
            byte[] bytes = Encoding.UTF8.GetBytes(code);
            SHA256Managed sha256 = new SHA256Managed();
            byte[] hash = sha256.ComputeHash(bytes);

            foreach (byte x in hash)
            {
                codeEncrypted += String.Format("{0:x2}", x);
            }

            return codeEncrypted;
        }

        private void updateIntentos(string user, int cant) 
        {
            Conexion sql = Conexion.getInstance();
            SqlCommand command;
            String setValues;

            if (cant == 3)
                setValues = "SET cantIntentos = @cant, inhabilitado = 'S' ";
            else
                setValues = "SET cantIntentos = @cant ";
            
            command = new SqlCommand("UPDATE b_sharp.usuarios " + setValues +
                                     "WHERE id_usuario = @id_usu", sql.openCon());

            command.Parameters.AddWithValue("@cant", cant);
            command.Parameters.AddWithValue("@id_usu", user);
            command.ExecuteNonQuery();
        }

        private void loginEnter(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
                loginButton_Click(sender, (EventArgs)e);
        }
    }
}
